'use strict';

const { logger } = require('ee-core/log');
const fs = require("fs");
const axios = require("axios");

/**
 * example
 * @class
 */
class RequestController {

    /**
     * 通用请求
     * @param config
     */

    async node_request (config) {
        config.headers = config.headers || {'Content-Type': 'application/json'}
        config.method = config.method || 'get'
        //上传文件
        if (config.file) {
            config.headers['Content-Type'] = 'multipart/form-data'
            const file = config.file
            let data = config.data || {}
            data[file.key] = fs.createReadStream(file.path)
            config.data = data
        }
        try {
            const res = await axios(config)
            if ([200, 201].includes(res.status) === false) {
                console.error("请求报错", config.url, JSON.stringify(res.data))
                throw "请求报错"
            }
            return res.data
        } catch (e) {
            console.error("请求报错", config, e.message)
            throw e.message
        }
    }
}
RequestController.toString = () => '[class RequestController]';

module.exports = RequestController;